//
//  PhotoBrowserViewController.swift
//  Weibo8023
//
//  Created by styshy on 15/12/20.
//  Copyright © 2015年 sz. All rights reserved.
//

import UIKit
import SVProgressHUD

private let PhotoBrowserCellId = "PhotoBrowserCellId"

class PhotoBrowserViewController: UIViewController {
    
    
    @objc private func close(){
        print("关闭图片浏览器")
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func save(){
        let cell = collectionView.visibleCells()[0] as! PhotoBrowerCell
        
        // 确保cell中一定有值
        guard let image = cell.imgView.image else{
            return
        }
        //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
        // 保存图片
        UIImageWriteToSavedPhotosAlbum(image,
            self,"image:didFinishSavingWithError:contextInfo:", nil)
        
        print("保存图片")
    }
    
    /**
     实现保存图片的代理方法
     
     - parameter image:       image
     - parameter error:       error
     - parameter contentInfo: contentInfo
     */
   @objc private func image(image:UIImage,didFinishSavingWithError error:NSError?, contextInfo:AnyObject?){
        let message = (error == nil) ? "保存成功" : "保存失败"
            SVProgressHUD.showInfoWithStatus(message)
    }
    
    // 将属性定义为必选属性，创建对象的时候初始化
    private var currentIndexPath:NSIndexPath
    private var picUrls = [NSURL]()
    
    init(indexPath:NSIndexPath, picUrls:[NSURL]){
        self.currentIndexPath = indexPath
        self.picUrls = picUrls
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
//        print(saveButton.frame)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        print("save\(saveButton.frame)")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        // 将视图滚动到选中的位置
        collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: false)
    }
    
    
    override func loadView() {
        var rect = UIScreen.mainScreen().bounds
        rect.size.width += 20
        let vc = UIView(frame: rect)
        view = vc
//        print(view)
        setupUI()
//        print(saveButton.frame)
        
    }
    
    // 设置colletionView的布局
    private class PhotoBrowserLayout:UICollectionViewFlowLayout{
        private override func prepareLayout() {
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            
            let rect = collectionView?.bounds
            itemSize = rect!.size
            collectionView?.bounces = false
            // 这个滚动的属性是scrollView的属性
            scrollDirection = .Horizontal
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.pagingEnabled = true

        }
    }
    
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout())
    
    private lazy var closeButton:UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), imageName: nil,backColor: UIColor.lightGrayColor())
    private lazy var saveButton:UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.lightGrayColor())
}

// MARK: - 界面设置
extension PhotoBrowserViewController{
    private func setupUI(){
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        // 设置自动布局
       collectionView.frame = view.bounds
        
        closeButton.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(view.snp_left).offset(8)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }

        
        // 新浪微博中保存按钮布局是参考view，当SnpKit发现saveButton的位置已经超出屏幕的时候，会自动做出调整位置。所以这边布局为 -8 的时候按钮的位置依然没有偏移除屏幕
        saveButton.snp_makeConstraints { (make) -> Void in
            make.right.equalTo(view.snp_right).offset(-28)
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        prepareCollectionView()
    }
    
    private func prepareCollectionView(){
        // 设置代理
        collectionView.dataSource = self
        // 注册cell
        collectionView.registerClass(PhotoBrowerCell.self, forCellWithReuseIdentifier: PhotoBrowserCellId)
    }
}

// MARK: - UICollectionViewDelegate 代理
extension PhotoBrowserViewController:PhotoBrowserDismissDelegate{
    
    func imageViewForDismiss() -> UIImageView {
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        let cell = collectionView.visibleCells()[0] as! PhotoBrowerCell
        iv.image = cell.imgView.image
        iv.frame = cell.scrollView.convertRect(cell.imgView.frame,
            toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return iv
    }
    
    func indexPathForDismiss() -> NSIndexPath {
        return collectionView.indexPathsForVisibleItems()[0]
    }
    
}

// MARK: - UICollectionViewDataSource 数据源
extension PhotoBrowserViewController:UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellId, forIndexPath: indexPath) as! PhotoBrowerCell
        
        cell.backgroundColor = UIColor.blackColor()
        
        cell.imageUrl = picUrls[indexPath.item]
        
        cell.photoDelegate = self
        
        return cell
    }
}


// MARK: - PhotoBrowserCellDelegate 代理
extension PhotoBrowserViewController:PhotoBrowserCellDelegate{
    func photoBrowserCellDidTapImage() {
        close()
    }
}
